package com.platform.common.logger.annotation;

import com.platform.common.logger.ILogger;
import com.platform.common.logger.impl.DebugLoggerFactory;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

import java.lang.reflect.Field;

/**
 * Created with IntelliJ IDEA.
 * User: wangyanginfo
 * Date: 12-9-5
 * Time: 上午9:35
 * To change this template use File | Settings | File Templates.
 */
@Service("loggerInjector")
public class LoggerInjector implements BeanPostProcessor {

    private static Logger logger = Logger.getLogger(LoggerInjector.class);

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    public Object postProcessBeforeInitialization(final Object bean, String beanName)
            throws BeansException {
        //logger.info("-- 日志注解初始化开始 --");
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
            public void doWith(Field field) throws IllegalArgumentException,
                    IllegalAccessException {
                // make the field accessible if defined private
                ReflectionUtils.makeAccessible(field);
                if (field.getAnnotation(EnableLogger.class) != null) {
                    String className = bean.getClass().getName();
                    Logger logger = Logger.getLogger(className);
                    field.set(bean, logger);
                }
                if (field.getAnnotation(DebugLogger.class) != null) {
                    String className = bean.getClass().getName();
                    ILogger logger = new DebugLoggerFactory().getLogger(className);
                    field.set(bean, logger);
                }
            }
        });
        //logger.info("-- 日志注解初始化完成 --");
        return bean;
    }

}
